const express = require('express');
const router = express.Router();
const managerModel = require('../../model/manager.js')
const svgCaptcha = require('svg-captcha')
const md5 = require('md5');
router.get('/',(req,res)=>{
    res.render('admin/login',{})
})
router.post('/dologin',async (req,res)=>{
    let username = req.body.username;
    let password = req.body.password;
    let verify = req.body.verify;
    // console.log(verify.toLowerCase())
    // console.log(username,password)
    if(verify.toLocaleLowerCase() != req.session.captcha.toLocaleLowerCase()){
        res.render('admin/status',{
            redirectUrl:'/admin/login',
            title:'验证码错误',
            message:'登录页面'
        })
        return;
    }
        // user是一个数组,数据库没有查到就是空数组；
        // [{"_id":"61c14e4d4bb27e3285920e87","username":"张三","password":"827ccb0eea8a706c4c34a16891f84e7b","__v":0}]
        let user = await managerModel.find({username,password:md5(password)})
        if(user.length>0){
            req.session.userinfo = user[0];
            res.render('admin/status',{
                redirectUrl:'/admin/main',
                title:'登录成功',
                message:'后台主页'
            })
        }else{
            res.render('admin/status',{
                redirectUrl:'/admin/login',
                title:'账号或密码错误',
                message:'登录页面'
            })
        }
       



   
})
router.get('/verify',(req,res)=>{
    var captcha = svgCaptcha.create();
    req.session.captcha = captcha.text;
    res.type('svg');
    res.status(200).send(captcha.data);
})
router.get('/loginout',(req,res)=>{
    req.session.userinfo = null;
    res.redirect('/admin/login')
})
module.exports = router;